module TunecoreDirect

  # Represents a response from the TC web service.  This class is designed to take a response from any method call in the API and create a
  # SDK object out of it.  It will look at the root XML node in the body of the HTTP response to determine the type of #object to return.
  #
  # When a response comes back from the TuneCore web service it is processed with this class.  The object being returned is extracted with the Response#object method.
  # You shouldn't have to use this class directly, as convenience methods are provided in the Person, Album, and Song classes.
  #
  # Any API object errors will be set in the errors accessor and the object type will be set in the type accessor.
  class TunecoreDirect::Response < TunecoreDirect::Base
    include TunecoreDirect
  
    attr_reader :type, :status, :errors
  
    # Accepts the body of the HTTP response from the TC web service.
    def initialize( body )
      @body = body
      @doc = REXML::Document.new( body )
      @type = @doc.root.name
      @status = @doc.root.elements["/*/status"].text

      if @status == "error"
        #collect the error messages and put them in an array of hashes
        @errors = @doc.root.elements.collect("/*/error"){|e| {:attribute => e.elements["attribute"].text, :message => e.elements["message"].text} }
      end
    end
  
    # Returns the appropriate object based on the complete response XML we got from the web service.  The object returned will be one of the following, based 
    # on what type of request you made:
    # * Person
    # * Album
    # * Song
    # * Array of people
    # * Array of albums
    # * Array of songs
    def object
      case @type
      when "person"
        person_element = @doc.root.elements["/person"]
        person = Person.from_xml_element( person_element)
        return person
      when "people"
        people = []
        @doc.root.elements.each("/people/person") do |person_element|
          people << Person.from_xml_element( person_element )
        end
        return people
      when "album"
        album_element = @doc.root.elements["/album"]
        album = Album.from_xml_element( album_element)
        return album
      when "albums"
        albums = []
        @doc.root.elements.each("/albums/album") do |album_element|
          albums << Album.from_xml_element( album_element )
        end
        return albums
      when "song"
        song_element = @doc.root.elements["/song"]
        song = Song.from_xml_element( song_element )
        return song
      when "songs"
        albums = []
        @doc.root.elements.each("/songs/song") do |song_element|
          songs << Song.from_xml_element( song_element )
        end
        return songs
      else
        raise "Unsupported response type: #{@type}"
      end
    end
    
    def to_xml
      @body
    end
      
  end
  
end